﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using AMM.Model;
using AMM.Model.Project;

namespace AMM.DataAccess.Project {
    public class BOMRepository : BaseRepository<BOM> {

        private int _pageSize;

        public BOMRepository(int pageSize) {
            this._pageSize = pageSize;
        }

        public BOM FetchBOMById(int bomId) {
            using (var ctx = this.Context) {
                return ctx.BOMs
                    .Include("BOMDetails")
                    .Include("BOMDetails.Material")
                    .FirstOrDefault(x => x.BOMId == bomId);
            }
        }

        public BOM FetchBOMByIdForView(int bomId) {
            using (var ctx = this.Context) {
                return ctx.BOMs
                    .Include("BOMDetails")
                    .Include("BOMDetails.Material")
                    .Include("BOMDetails.Basic")
                    .FirstOrDefault(x => x.BOMId == bomId);
            }
        }

        public void UpdateBOM(BOM bom, BOM oldBOM) {
            using (var ctx = this.Context) {
                using (DbContextTransaction trans = ctx.Database.BeginTransaction()) {
                    try {
                        bom.BOMDetails.Where(x => x.ClassStatus == ClassStatus.Added).ToList().ForEach(x => {
                            x.BOM = bom;
                            x.BOMId = bom.BOMId;
                            x.BOMDetailsId = Guid.NewGuid().GetHashCode();
                        });
                        // do not try to merge with above codes, because you can't change the fields which was marked as primary key
                        bom.BOMDetails.ToList().ForEach(x => {
                            ctx.BOMDetails.Attach(x);
                            switch (x.ClassStatus) {
                                case ClassStatus.UnChanged:
                                    ctx.BOMDetails.Attach(x);
                                    ctx.Entry(x).State = EntityState.Unchanged;
                                    break;
                                case ClassStatus.Updated:
                                    x.ModifiedBy = bom.ModifiedBy;
                                    x.ModifiedDatetime = DateTime.Now;
                                    ctx.BOMDetails.Attach(x);
                                    ctx.Entry(x).State = EntityState.Modified;
                                    break;
                                case ClassStatus.Added:
                                    x.CreatedBy = bom.ModifiedBy;
                                    x.CreatedDatetime = DateTime.Now;
                                    ctx.BOMDetails.Attach(x);
                                    ctx.Entry(x).State = EntityState.Added;
                                    break;
                                case ClassStatus.Deleted:
                                    ctx.BOMDetails.Attach(x);
                                    ctx.Entry(x).State = EntityState.Deleted;
                                    break;
                            }
                        });

                        ctx.BOMs.Add(bom);
                        ctx.Entry(bom).State = EntityState.Modified;
                        ctx.SaveChanges();
                        trans.Commit();
                    }
                    catch (Exception ex) {
                        trans.Rollback();
                        throw ex;
                    }
                }
            }
        }

        public void DeleteMultipleBOM(params int[] bomIds) {
            using (var ctx = this.Context) {
                using (DbContextTransaction trans = ctx.Database.BeginTransaction()) {
                    try {
                        ctx.BOMDetails.Where(x => bomIds.Contains(x.BOMId)).ToList().ForEach(x => {
                            ctx.BOMDetails.Remove(x);
                        });
                        ctx.BOMs.Where(x => bomIds.Contains(x.BOMId)).ToList().ForEach(x => {
                            ctx.BOMs.Remove(x);
                        });
                        ctx.SaveChanges();
                        trans.Commit();
                    }
                    catch (Exception ex) {
                        trans.Rollback();
                        throw ex;
                    }
                }
            }
        }

        public List<BOM> FetchBOMList(BOMSearchModel searchModel, int pageIndex) {
            using (var ctx = this.Context) {
                var query = ctx.BOMs
                    .Include("BOMDetails")
                    .Include("BOMDetails.Material")
                    .Where(x => !string.IsNullOrEmpty(x.Code));

                if (!string.IsNullOrEmpty(searchModel.Code)) {
                    query = query.Where(x => x.Code.Contains(searchModel.Code));
                }
                if (!string.IsNullOrEmpty(searchModel.MaterialCode)) {
                    query = query.Where(x => x.BOMDetails.Any(y => y.Material.Code.Contains(searchModel.MaterialCode)));
                }
                if (searchModel.CreateDateStart.HasValue) {
                    query = query.Where(x => x.CreatedDatetime >= DbFunctions.TruncateTime(searchModel.CreateDateStart.Value));
                }
                if (searchModel.CreateDateEnd.HasValue) {
                    query = query.Where(x => x.CreatedDatetime <= DbFunctions.TruncateTime(searchModel.CreateDateEnd.Value));
                }
                if (searchModel.BOMStatus.HasValue) {
                    query = query.Where(x => x.BOMStatus == searchModel.BOMStatus.Value);
                }

                searchModel.Records = query.Count();
                pageIndex = (pageIndex - 1) * this._pageSize > searchModel.Records ? 1 : pageIndex;

                return query.OrderByDescending(x => x.CreatedDatetime).Skip((pageIndex - 1) * this._pageSize).Take(this._pageSize).ToList();
            }
        }
    }
}
